<template>
  <div class="w-full h-full relative">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="absolute inset-0 flex items-center justify-center bg-slate-900/50 rounded-lg">
      <div class="flex flex-col items-center space-y-3">
        <div class="w-8 h-8 border-3 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
        <span class="text-sm text-slate-300">加载趋势数据...</span>
      </div>
    </div>
    
    <!-- 错误状态 -->
    <div v-if="hasError" class="absolute inset-0 flex items-center justify-center bg-slate-900/50 rounded-lg">
      <div class="flex flex-col items-center space-y-3 text-center">
        <div class="w-8 h-8 bg-red-500/20 rounded-full flex items-center justify-center">
          <svg class="w-4 h-4 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
        </div>
        <span class="text-sm text-slate-300">图表加载失败</span>
        <button 
          @click="retryLoad"
          class="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs rounded transition-colors"
        >
          重试
        </button>
      </div>
    </div>
    
    <!-- 图表画布 -->
    <canvas ref="chartCanvas" class="w-full h-full"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'

const props = defineProps({
  charts: {
    type: Array,
    default: () => []
  },
  layout: {
    type: String,
    default: 'horizontal' // horizontal, vertical
  },
  isLoading: {
    type: Boolean,
    default: false
  },
  hasError: {
    type: Boolean,
    default: false
  }
})

const chartCanvas = ref(null)
let chart = null

// 重试加载函数
const retryLoad = () => {
  // 触发重新渲染
  drawChart()
}

// 扩展颜色配置 - 基于#3b82f6扩展协调色系
const colorMap = {
  blue: {
    border: 'rgb(59, 130, 246)',
    background: 'rgba(59, 130, 246, 0.1)',
    gradient: ['rgba(59, 130, 246, 0.3)', 'rgba(59, 130, 246, 0.05)']
  },
  lightBlue: {
    border: 'rgb(96, 165, 250)',
    background: 'rgba(96, 165, 250, 0.1)',
    gradient: ['rgba(96, 165, 250, 0.3)', 'rgba(96, 165, 250, 0.05)']
  },
  darkBlue: {
    border: 'rgb(29, 78, 216)',
    background: 'rgba(29, 78, 216, 0.1)',
    gradient: ['rgba(29, 78, 216, 0.3)', 'rgba(29, 78, 216, 0.05)']
  },
  green: {
    border: 'rgb(16, 185, 129)',
    background: 'rgba(16, 185, 129, 0.1)',
    gradient: ['rgba(16, 185, 129, 0.3)', 'rgba(16, 185, 129, 0.05)']
  },
  purple: {
    border: 'rgb(139, 92, 246)',
    background: 'rgba(139, 92, 246, 0.1)',
    gradient: ['rgba(139, 92, 246, 0.3)', 'rgba(139, 92, 246, 0.05)']
  },
  orange: {
    border: 'rgb(245, 158, 11)',
    background: 'rgba(245, 158, 11, 0.1)',
    gradient: ['rgba(245, 158, 11, 0.3)', 'rgba(245, 158, 11, 0.05)']
  },
  red: {
    border: 'rgb(239, 68, 68)',
    background: 'rgba(239, 68, 68, 0.1)',
    gradient: ['rgba(239, 68, 68, 0.3)', 'rgba(239, 68, 68, 0.05)']
  },
  teal: {
    border: 'rgb(20, 184, 166)',
    background: 'rgba(20, 184, 166, 0.1)',
    gradient: ['rgba(20, 184, 166, 0.3)', 'rgba(20, 184, 166, 0.05)']
  },
  indigo: {
    border: 'rgb(99, 102, 241)',
    background: 'rgba(99, 102, 241, 0.1)',
    gradient: ['rgba(99, 102, 241, 0.3)', 'rgba(99, 102, 241, 0.05)']
  }
}

// 创建渐变
const createGradient = (ctx, chartArea, colors) => {
  const gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top)
  gradient.addColorStop(0, colors[1])
  gradient.addColorStop(1, colors[0])
  return gradient
}

// 绘制单个图表
const drawSingleChart = (ctx, data, color, chartArea, index, totalCharts) => {
  if (!data || !data.length) return
  
  const colors = colorMap[color] || colorMap.blue
  const { left, top, width, height } = chartArea
  
  // 计算子图表区域
  let subChartArea
  if (props.layout === 'horizontal') {
    const subWidth = width / totalCharts
    subChartArea = {
      left: left + subWidth * index,
      top: top,
      width: subWidth,
      height: height
    }
  } else {
    const subHeight = height / totalCharts
    subChartArea = {
      left: left,
      top: top + subHeight * index,
      width: width,
      height: subHeight
    }
  }
  
  // 添加内边距
  const padding = 16
  const drawArea = {
    left: subChartArea.left + padding,
    top: subChartArea.top + padding,
    width: subChartArea.width - padding * 2,
    height: subChartArea.height - padding * 2
  }
  
  if (drawArea.width <= 0 || drawArea.height <= 0) return
  
  // 计算数据范围
  const maxValue = Math.max(...data.map(d => d.value))
  const minValue = Math.min(...data.map(d => d.value))
  const range = maxValue - minValue || 1
  
  // 绘制标题
  ctx.fillStyle = '#ffffff'
  ctx.font = '14px sans-serif'
  ctx.textAlign = 'left'
  ctx.fillText(data[0]?.chartTitle || `图表 ${index + 1}`, drawArea.left, drawArea.top - 5)
  
  // 绘制网格线
  ctx.strokeStyle = 'rgba(148, 163, 184, 0.2)'
  ctx.lineWidth = 1
  
  // 水平网格线
  for (let i = 0; i <= 4; i++) {
    const y = drawArea.top + (drawArea.height / 4) * i
    ctx.beginPath()
    ctx.moveTo(drawArea.left, y)
    ctx.lineTo(drawArea.left + drawArea.width, y)
    ctx.stroke()
  }
  
  // 垂直网格线
  const stepX = drawArea.width / (data.length - 1)
  data.forEach((_, i) => {
    const x = drawArea.left + stepX * i
    ctx.beginPath()
    ctx.moveTo(x, drawArea.top)
    ctx.lineTo(x, drawArea.top + drawArea.height)
    ctx.stroke()
  })
  
  // 绘制区域填充
  ctx.beginPath()
  data.forEach((item, i) => {
    const x = drawArea.left + stepX * i
    const y = drawArea.top + drawArea.height - ((item.value - minValue) / range) * drawArea.height
    if (i === 0) ctx.moveTo(x, y)
    else ctx.lineTo(x, y)
  })
  
  // 填充区域
  ctx.lineTo(drawArea.left + drawArea.width, drawArea.top + drawArea.height)
  ctx.lineTo(drawArea.left, drawArea.top + drawArea.height)
  ctx.closePath()
  
  const gradient = ctx.createLinearGradient(0, drawArea.top, 0, drawArea.top + drawArea.height)
  gradient.addColorStop(0, colors.gradient[0])
  gradient.addColorStop(1, colors.gradient[1])
  ctx.fillStyle = gradient
  ctx.fill()
  
  // 绘制线条
  ctx.beginPath()
  data.forEach((item, i) => {
    const x = drawArea.left + stepX * i
    const y = drawArea.top + drawArea.height - ((item.value - minValue) / range) * drawArea.height
    if (i === 0) ctx.moveTo(x, y)
    else ctx.lineTo(x, y)
  })
  
  ctx.strokeStyle = colors.border
  ctx.lineWidth = 2
  ctx.lineJoin = 'round'
  ctx.lineCap = 'round'
  ctx.stroke()
  
  // 绘制数据点
  data.forEach((item, i) => {
    const x = drawArea.left + stepX * i
    const y = drawArea.top + drawArea.height - ((item.value - minValue) / range) * drawArea.height
    
    // 外圈
    ctx.beginPath()
    ctx.arc(x, y, 4, 0, Math.PI * 2)
    ctx.fillStyle = '#1e293b'
    ctx.fill()
    ctx.strokeStyle = colors.border
    ctx.lineWidth = 2
    ctx.stroke()
    
    // 内圈
    ctx.beginPath()
    ctx.arc(x, y, 2, 0, Math.PI * 2)
    ctx.fillStyle = colors.border
    ctx.fill()
    
    // 添加数据点边框
    ctx.strokeStyle = '#ffffff'
    ctx.lineWidth = 2
    ctx.stroke()
  })
  
  // 绘制坐标轴标签
  ctx.fillStyle = '#94a3b8'
  ctx.font = '11px sans-serif'
  ctx.textAlign = 'center'
  
  // X轴标签（只显示偶数索引，避免拥挤）
  data.forEach((item, i) => {
    if (i % 2 === 0) {
      const x = drawArea.left + stepX * i
      const y = drawArea.top + drawArea.height + 15
      ctx.fillText(item.label, x, y)
    }
  })
  
  // Y轴标签
  ctx.textAlign = 'right'
  ctx.fillStyle = '#94a3b8'
  ctx.font = '11px sans-serif'
  for (let i = 0; i <= 5; i++) {
    const value = Math.round((maxValue / 5) * (5 - i))
    const y = drawArea.top + (drawArea.height / 5) * i + 3
    ctx.fillText(value.toString(), drawArea.left - 10, y)
  }
}

// 绘制图表
const drawChart = () => {
  if (!chartCanvas.value || !props.charts.length) return
  
  const ctx = chartCanvas.value.getContext('2d')
  
  // 清除之前的图表
  if (chart) {
    chart.destroy()
  }
  
  // 设置高DPI支持
  const rect = chartCanvas.value.getBoundingClientRect()
  const dpr = window.devicePixelRatio || 1
  chartCanvas.value.width = rect.width * dpr
  chartCanvas.value.height = rect.height * dpr
  ctx.scale(dpr, dpr)
  
  // 清空画布
  ctx.clearRect(0, 0, rect.width, rect.height)
  
  // 设置边距
  const padding = { top: 20, right: 20, bottom: 40, left: 50 }
  const chartWidth = rect.width - padding.left - padding.right
  const chartHeight = rect.height - padding.top - padding.bottom
  
  // 绘制图表标题
  ctx.fillStyle = '#ffffff'
  ctx.font = 'bold 14px sans-serif'
  ctx.textAlign = 'center'
  ctx.fillText('多指标趋势分析', rect.width / 2, 15)
  
  // 绘制网格线
  ctx.strokeStyle = 'rgba(148, 163, 184, 0.2)'
  ctx.lineWidth = 1
  
  // 垂直网格线
  for (let i = 0; i <= 10; i++) {
    const x = padding.left + (chartWidth / 10) * i
    ctx.beginPath()
    ctx.moveTo(x, padding.top)
    ctx.lineTo(x, padding.top + chartHeight)
    ctx.stroke()
  }
  
  // 水平网格线
  for (let i = 0; i <= 5; i++) {
    const y = padding.top + (chartHeight / 5) * i
    ctx.beginPath()
    ctx.moveTo(padding.left, y)
    ctx.lineTo(padding.left + chartWidth, y)
    ctx.stroke()
  }
  
  // 计算主绘图区域
  const chartArea = {
    left: padding.left,
    top: padding.top,
    width: chartWidth,
    height: chartHeight
  }
  
  // 绘制每个子图表
  props.charts.forEach((chartData, index) => {
    if (chartData && chartData.data) {
      drawSingleChart(ctx, chartData.data, chartData.color || 'blue', chartArea, index, props.charts.length)
    }
  })
  
  // 绘制边框
  ctx.strokeStyle = 'rgba(59, 130, 246, 0.2)'
  ctx.lineWidth = 1
  ctx.strokeRect(chartArea.left, chartArea.top, chartArea.width, chartArea.height)
}

// 监听数据变化
watch(() => props.charts, () => {
  drawChart()
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  drawChart()
}

onMounted(() => {
  // 设置canvas尺寸
  const rect = chartCanvas.value.getBoundingClientRect()
  chartCanvas.value.width = rect.width * window.devicePixelRatio
  chartCanvas.value.height = rect.height * window.devicePixelRatio
  
  const ctx = chartCanvas.value.getContext('2d')
  ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
  
  drawChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chart) {
    chart.destroy()
  }
})
</script>

<style scoped>
canvas {
  display: block;
  width: 100% !important;
  height: 100% !important;
}
</style>